package gobase

import (
	"bytes"
	"math"
	"strings"
)

func Trim(s string) string {
	return strings.Trim(s, " \r\n\t")
}

func TryTrimPrefix(s, prefix string) (newstr string, ok bool) {
	if len(prefix) == 0 {
		return s, false
	}

	if !strings.HasPrefix(s, prefix) {
		return s, false
	}
	return s[len(prefix):], true
}

func TryTrimSuffix(s, suffix string) (newstr string, ok bool) {
	if len(suffix) == 0 {
		return s, false
	}
	if !strings.HasSuffix(s, suffix) {
		return s, false
	}
	return s[:len(s)-len(suffix)], true
}

// 截掉前后字符
func TryTrimQuoteChr(s string, prefix, suffix byte) (string, bool) {
	l := len(s)
	if l <= 2 || s[0] != prefix || s[l-1] != suffix {
		return s, false
	}

	return s[1 : l-1], true
}

func LeftStr(s string, n int) string {
	strBuf := []rune(s)
	if len(strBuf) < n {
		n = len(strBuf)
	}
	s1 := string(strBuf[:n])
	return s1
}

func AddSuffixForWidth(src string, width int, suffix string) string {
	disl := width - len(src)
	if disl < 0 {
		return src
	}
	fixl := len(suffix)
	if fixl == 0 {
		suffix = " "
		fixl = 1
	}

	if fixl == 1 {
		rep := bytes.Repeat([]byte(suffix), disl)
		str := src + string(rep)
		return str
	} else {
		l := int(math.Ceil(float64(disl) / float64(fixl)))
		rep := bytes.Repeat([]byte(suffix), l)
		str := src + string(rep[:disl])
		return str
	}

}

func AddPrefixForWidth(src string, width int, prefix string) string {
	disl := width - len(src)
	if disl <= 0 {
		return src
	}
	fixl := len(prefix)
	if fixl == 0 {
		prefix = " "
		fixl = 1
	}

	if fixl == 1 {
		rep := bytes.Repeat([]byte(prefix), disl)
		str := string(rep) + src
		return str
	} else {
		l := int(math.Ceil(float64(disl) / float64(fixl)))
		rep := bytes.Repeat([]byte(prefix), l)
		str := string(rep[:disl]) + src
		return str
	}
}
